# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) YYYY Alexandros Fotiadis fotiadis90@gmail.com
# This program is free software: you can redistribute it and/or modify it 
# under the terms of the GNU General Public License version 3, as published 
# by the Free Software Foundation.
# 
# This program is distributed in the hope that it will be useful, but 
# WITHOUT ANY WARRANTY; without even the implied warranties of 
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR 
# PURPOSE.  See the GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along 
# with this program.  If not, see <http://www.gnu.org/licenses/>.
### END LICENSE

from gettext import gettext as _
import os
Home = os.getenv("HOME")
AppName = 'android_keyboard'
homeDir = Home + '/.androidKeyboard'
if(os.path.isdir(homeDir) == False):os.system('mkdir '+homeDir)

def log():
    import logging

    logger = logging.getLogger(AppName)
    #logging.basicConfig(format='%(asctime)s:%(levelname)s:%(name)s:%(message)s')
    return logger

def ReadConfig(FileName,section,option):
    import ConfigParser,os
    logger = log() #Run Logger

    if(os.path.isfile(homeDir+'/'+FileName) == False):
        logger.warning(_('File not Founded'))
        return False

    Config = ConfigParser.ConfigParser()
    Config.optionxform=str
    Config.read(homeDir+'/'+FileName)
    logger.debug(_('Read Config File')+' '+str(FileName))
    if(section != None):
        try:
            ReturnValue = Config.options(section)
            logger.debug(_('Insert to section')+' -> '+str(ReturnValue))
        except ConfigParser.NoSectionError:
            return False
        if(option != None):
            ReturnValue = Config.get(section, option)
            if(ReturnValue == None):return False
            logger.debug(_('Insert to section')+' -> '+str(ReturnValue))
        return ReturnValue
    return Config

def SaveConfig(FileName,section,options): #File = test.ini; section = 'MainSettings'; Options(Array) option: value;
    import ConfigParser,os
    logger = log() #Run Logger
    #CheckFile
    if(os.path.isfile(homeDir+'/'+FileName) == False):
        os.system('touch '+homeDir+'/'+FileName)

    ##Sections Check
    if(section == None):
        logger.warning('No Section/Profile Name : ' + str(section))
        return False
    if(len(section) <= 0):
        logger.warning('No Section/Profile Name')
        return False

    Config = ConfigParser.SafeConfigParser() #Read Config
    logger.debug('Save of '+str(FileName)+' the Sections : '+str(section))
    Config.optionxform=str
    Config.read(homeDir+'/'+FileName)
    ExistsSec = Config.sections()

    try:
        ExistsSec.index(section)
        logger.debug('Section '+str(section)+' already exists, will recreate')
        Exists = True
    except ValueError:
        logger.debug('Section '+str(section)+' not on '+str(FileName)+' maked New')
        Exists = False
    ConfigFile = open(homeDir+'/'+FileName,'w')

    if(Exists):
        for option in options: #Add
            if(options[option] == ''):
                options[option] = 'None'
            Config.set(section, option, options[option])
        Config.write(ConfigFile)
        ConfigFile.close()
    else:
        Config.add_section(section)
        for option in options: #Add
            if(options[option] == ''):
                options[option] = 'None'
            Config.set(section, option, options[option])

        Config.write(ConfigFile)
        logger.debug('Write ConfigFile Finished')
        ConfigFile.close()

def RemoveSection(FileName,section):
    import ConfigParser
    logger = log() #Run Logger

    logger.debug('Remove the Section '+str(section)+'of the File: '+str(FileName))
    Config = ConfigParser.SafeConfigParser() #Read Config
    Config.optionxform=str
    Config.read(homeDir+'/'+FileName)
    ConfigFile = open(homeDir+'/'+FileName,'w')
    ExistsSec = Config.sections()

    try:
        ExistsSec.index(section)
        logger.debug('Section '+str(section)+' Founded')
    except ValueError:
        logger.warning('Section not on File found')
        return False

    Config.remove_section(section)
    ExistsSec = Config.sections()

    Config.write(ConfigFile)
    logger.debug('Write ConfigFile Finished')
    ConfigFile.close()
    return True

def ReadSSHConfigHosts(File):
    import os,sys
    logger = log() #Run Logger
    if(os.path.isfile(File) == False):
        logger.debug('SSH Config File on '+File+' not Founded')
        return False

    ConfigProfileOutput = os.popen("cat "+File+" | grep 'Host '").read()

    if(len(ConfigProfileOutput) <= 0):
        return False

    Hosts = ConfigProfileOutput.split('\n')

    ReturnHost = []
    logger.debug('Read Hosts on the Config File')
    for Host in Hosts:
        if(len(Host) <= 0):
            continue
        HostName = Host.replace('Host ', '')

        ReturnHost.append(HostName)

    return ReturnHost

def Notifyc(MSG):
    from gi.repository import Notify
    logger = log() #Run Logger
    Notify.init(AppName)
    n = Notify.Notification.new(AppName, MSG, 'stock_view-details')
    n.show()

def CurrentIPAddress():
    import urllib as urllibReq
    logger = log()
    logger.debug('Request Current IPAddress from "http://fotiadis90.dyndns.org/SS/getEXTIP"')
    f = urllibReq.urlopen("http://fotiadis90.dyndns.org/SS/getEXTIP")
    pub_ip = f.read()
    f.close()
    logger.debug('Server Answer : "'+pub_ip+'"')
    return pub_ip

def SSHConnectionCheck(method,name,password,ip):
    import os
    logger = log() #Run Logger
    TimeOut = 2
    logger = log()
    logger.debug('Server Connecting check..')
    if(method == 'SSHP'):
        logger.debug('SSH Profile : '+name)
        Answer = timeout_command('ssh '+name+' echo "i-am-online"', TimeOut)
        if(Answer == False):
            return False
        elif(Answer == 'i-am-online'):
            return True
    elif(method == 'alt'):
        logger.debug('Server IP : '+ip+' Username :'+name)
        Answer = timeout_command('sshpass -p '+password+' ssh '+name+'@'+ip+' echo "i-am-online"', TimeOut)
        if(Answer == False):
            return False
        elif(Answer == 'i-am-online'):
            logger.debug('Log to the Server was surrcessfully')
            return True

    else:
        logger.warning('Unaccepted method')
        return

def timeout_command(command, timeout):
    """call shell-command and either return its output or kill it
    if it doesn't normally exit within timeout seconds and return None"""

    import subprocess, datetime, os, time, signal
    logger = log() #Run Logger
    command = command.split()
    start = datetime.datetime.now()
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    while process.poll() is None:

      time.sleep(0.200)
      now = datetime.datetime.now()
      if (now - start).seconds> timeout:
        os.kill(process.pid, signal.SIGKILL)
        os.waitpid(-1, os.WNOHANG)
        return False
    OutPut = process.stdout.read()
    return OutPut.replace("\n", "")

def mountCheck(path):
    import os
    logger = log() #Run Logger
    logger.debug('Check if '+path+' are Mounted')
    out = os.popen("mount -l | grep '"+path+"'").read()
    if len(out) > 2:
        logger.debug(path+' is Mounted')
        return True
    else:
        logger.debug(path+' are not Mounted')
        return False

def InstallCheck(appName):
    import os
    logger = log() #Run Logger

    logger.debug('Check installed Application '+appName)

    Output = os.popen('dpkg -l | grep "ii  '+appName+' "').read()

    if(len(Output) < 1):
        return False
    else:
        return True

def findThisProcess(process_name):
    #Check if Proccess is running
    logger = log() #Run Logger
    logger.debug('Check Process '+process_name)
    output = os.popen('ps -e | grep " '+process_name+'"').read()

    if(len(output) < 2):
        logger.debug('Process '+process_name+' not Running')
        return False
    else:
        logger.debug('Process '+process_name+' is Running')
        return True

def ConnecitonCheck(ip,port):
    import urllib2,socket


    try:
        response=urllib2.urlopen('http://'+str(ip)+':'+str(port),timeout=1)
        return True
    except socket.error: return False
    except socket.timeout: return False
    except UnicodeEncodeError: return False
    except urllib2.URLError: return False
